import pygame
import sys

# 初始化 pygame
pygame.init()

# 设置窗口大小和标题
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Pygame 示例 - 控制移动的球")

# 定义颜色
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)

# 定义球的初始位置和速度
ball_x = 300
ball_y = 200
ball_speed_x = 3
ball_speed_y = 3
ball_radius = 20

# 主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:  # 检查退出事件
            running = False

    # 更新球的位置
    ball_x += ball_speed_x
    ball_y += ball_speed_y

    # 检测边界并反弹
    if ball_x - ball_radius < 0 or ball_x + ball_radius > 600:
        ball_speed_x = -ball_speed_x
    if ball_y - ball_radius < 0 or ball_y + ball_radius > 400:
        ball_speed_y = -ball_speed_y

    # 绘制屏幕
    screen.fill(BLACK)
    pygame.draw.circle(screen, BLUE, (ball_x, ball_y), ball_radius)

    # 更新显示
    pygame.display.flip()
    pygame.time.delay(20)  # 延时控制速度

# 退出程序
pygame.quit()
sys.exit()
